/**
 * 上传广告---编辑图片广告
 */
function editAd(){

	var adId = getQueryString("adId");
	$.ajax({
		url : '/web-adv/editAd',
        data:{adId:adId},
		type : 'post',
		success : function(data) {
			var resultVo = data.resultVo;
			var picServerPrex = resultVo.picServerPrex;
			var ads = data.bean;
			$("#advUrl").html(ads.advUrl); //广告链接
			$("#adName").html(ads.adName);	
			$(".adCoverImg").attr("src",picServerPrex+ads.adHomepage);

			//关键字
			var adKeys = ads.adKey.split(" ");
			for(var i =0;i<adKeys.length;i++){
				if(adKeys[i].length !=0){
					$(".adKeyword").append("<span>"+adKeys[i]+"</span>");
				}
			}

			//描述
			$(".adDescribe").html(ads.description);
			//轮播
			var terminalType = ads.terminalType;
			var urls = "";
			switch (terminalType) {
			   case "mobile":
				   urls = ads.mobileVUrl;
			     break;
			   case "pc":
				   urls =ads.pcVUrl;
			     break;
			   case "pad":
				   urls =ads.padVUrl;
			     break;
			   case "tv":
				   urls =ads.tvVUrl;
			     break;
			   default:
				   urls ="";
			}
			var urlArr = urls.split("|");
			for(var i=0;i<urlArr.length;i++){
				if(urlArr[i].length != 0){
					var lis = "<li class='left'>"+
					"<img src='"+picServerPrex+urlArr[i]+"' alt=''/>"+
					 "<div class='closedIcon'></div>"+
					 "<div class='adCoverFilmsBtnGroup'>"+
						 "<button class='btn btn-primary left'  onclick='flashImg.goSetting($(this))' data-toggle='modal' data-target='.flashImgSettingModal'>设为封面图</button>"+
					     "<button class='btn btn-primary right' onclick='flashImg.edit($(this))' data-toggle='modal' data-target='.flashImgEditModal'>修改</button>"+
						 "<div class='clear'></div>"+
					 "</div>"+
					 "<div class='closedIcon' onclick='flashImg.delegate($(this))' data-toggle='modal' data-target='.flashImgDelegateModal'>X</div>"+
					"</li>";
					$(".adCoverFilmsWrap").append(lis);
				}
			}

			
			//广告属性标签
			var classfyIds = ads.adClassify.split("|");
			for(var i =0;i<classfyIds.length;i++){
				if(classfyIds[i].length != 0){
					//console.log(classfyIds[i]);
					var li = "<li><img id=\""+classfyIds[i]+"\" src=\"/web-adv/advWeb/static/images/genres_pic"+classfyIds[i]+".png\"alt=\"\" /></li>";
					$("#adClassify").append(li);
				}
			}
			
			//终端  （mobile，pc，pad，tv）手机、PC、PAD、互联网电视
			var terminalType = ads.terminalType; //终端
			switch(terminalType){
				case 'mobile':
					$("#left :nth-child(1)").attr("src","/web-adv/advWeb/static/images/mobileIcon.png");
					$("#left :nth-child(2)").html("手机");
					$("#size").html(ads.mobileSize);
					break
				case 'pc':
					$("#left :nth-child(1)").attr("src","/web-adv/advWeb/static/images/pcIcon.png");
					$("#left :nth-child(2)").html("PC");
					$("#size").html(ads.pcSize);
					break
				case 'pad':
					$("#left :nth-child(1)").attr("src","/web-adv/advWeb/static/images/padIcon.png");
					$("#left :nth-child(2)").html("PAD");
					$("#size").html(ads.padSize);
					break
				case 'tv':
					$("#left :nth-child(1)").attr("src","/web-adv/advWeb/static/images/tvIcon.png");
					$("#left :nth-child(2)").html("互联网电视");
					$("#size").html(ads.tvSize);
					break
				default:
			}
		},
        error: function(){}        
	});
}

/**
 *  提交审核
 */
var pictureUrls = "";//图片路径集
var pictureUrl = "";//保存后返回的路径
var adHomePageUrl ="";
function updateAd(){
	var adId = getQueryString("adId");
	var terminalType = getQueryString("terminalType");
	var adUrl=$(".adUrl").text();
	var description = $(".adDescribe").text();
	var adHomeimage = $("#adHomeimage").attr("src");
	var adKey="";
	var adKeys = $(".adKeyword").find("span");
	for(var i =0;i<adKeys.length;i++){
		adKey += adKeys.eq(i).html()+"|";
	}

	//广告属性
	var adClassify = "";
	var Achecked=$(".adTarget img");
	$.each(Achecked,function(index){
		var src = Achecked[index].src;
		adClassify +=src.substring(src.lastIndexOf(".")-4,src.lastIndexOf("."))+"|";
	});

	//判断封面是否修改
	//封面修改了，为自己上传修改的图片
	if(adHomeimage.indexOf("data:image") !=-1){
		//轮播图 路径
		var imgs = new Array();
		var i=0;
		$(".adCoverFilmsWrap img").each(function(){
			if($(this).attr("src").indexOf("data:image") != -1 ){//base64编码的
				imgs[i] = $(this).attr("src") ;
			}else{//不是base64编码的
				pictureUrls += $(this).attr("src").split("/pictures/")[1]+"|";
			}
			i++;
		});
		var duration =  pictureUrls.split("|").length-1;
		//保存广告图片(轮播图片有修改)
			$.ajax({//提交
				url : '/web-adv/updateAd',
				data:{
					 id:adId,
					 adHomepage:adHomePageUrl,
					 adKey:adKey,
					 description:description,
					 adClassify:adClassify,
					 terminalType:terminalType,
					 pictureUrl:pictureUrls,
					duration:duration,
					advUrl:adUrl
				  },
				type : 'post',
				success : function(data) {
					if(data.status=="1"){
						window.location.href="/web-adv/advWeb/views/uploadAd/imageAd/uploadCheck.html?selectedNav=1&navPos=2&adId="+adId+")";
					}else{
						alert("保存失败！")
					}
				},
				error: function(){}
			});

	}else{//封面没有修改（src不为base64），这时可能为轮播图片替换的，也可以没有替换。所以这时需要切割保存
		//切割 赋值
		adHomePageUrl = $("#adHomeimage").attr("src").split("/pictures/")[1];
		//判断广告图片是否修改
		var imgs = new Array();
		var i=0;
		$(".adCoverFilmsWrap img").each(function(){
			if($(this).attr("src").indexOf("data:image") != -1 ){//base64编码的
				imgs[i] = $(this).attr("src") ;
			}else{//不是base64编码的
				pictureUrls += $(this).attr("src").split("/pictures/")[1]+"|";
			}
			 i++;
		});
		var duration =  pictureUrls.split("|").length-1;
		//保存广告图片
		$.ajax({//提交
			url : '/web-adv/updateAd',
			data:{
				 id:adId,
				 adKey:adKey,
				 description:description,
				 adClassify:adClassify,
				 terminalType:terminalType,
				 pictureUrl:pictureUrls,
				 adHomepage:adHomePageUrl,
				duration:duration,
				advUrl:adUrl
			  },
			type : 'post',
			success : function(data) {
				if(data.status=="1"){
					window.location.href="/web-adv/advWeb/views/uploadAd/imageAd/uploadCheck.html?selectedNav=1&navPos=2&adId="+adId+")";
				}else{
					alert("保存失败！")
				}
			},
			error: function(){}
		});

	}
	
}
function dataURItoBlob(dataURI) {
	var byteString = atob(dataURI.split(',')[1]);
	var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
	var ab = new ArrayBuffer(byteString.length);
	var ia = new Uint8Array(ab);
	for (var i = 0; i < byteString.length; i++) {
		ia[i] = byteString.charCodeAt(i);
	}
	return new Blob([ab], {type: mimeString});
}
var flashImg = {

	index:0,  //图片索引
	leftClick:function(){
		flashImg.index++;
		var imgLength = Math.ceil($("ul.adCoverFilmsWrap").find("li").length/3);
		if(flashImg.index==imgLength){  //归零
			flashImg.index = 0;
		}
		$("ul.adCoverFilmsWrap").stop().animate({left:-flashImg.index*1035-15});
	},
	rightClick:function(){
		flashImg.index--;
		var imgLength = Math.ceil($("ul.adCoverFilmsWrap").find("li").length/3);
		if(flashImg.index<0){  //归零
			flashImg.index = imgLength-1;
		}
		$("ul.adCoverFilmsWrap").stop().animate({left:-flashImg.index*1035-15});
	},
	delegateDom:"",
	delegate:function(ele){
		flashImg.delegateDom = ele;
	},
	isDelegate:function(ele){
		flashImg.delegateDom.parent("li").remove();
		ele.next().trigger("click");
	},
	editDom:"",
	edit:function(ele){
		flashImg.editDom = ele;
	},
	//封面图片
	editUpload:function(e,ele){
		var fs = new FileReader(),files = e.files[0];
		var fileName = files.name;
		if(files.size>10*1024*1024 ||files.size<10*1024 ){
			console.log("======封面====="+files.size)
			alert("单照图片在10K-10M之间，请您重新选择图片！");
		}else {
			if(!flashImg.isSuffix(fileName)) return false;//判断图片格式
			fs.readAsDataURL(files);
			fs.onload = function (event) {
				ele.parent("div.form-inline").next("div").find("img").attr("src",this.result);
				ele.parent("div.form-inline").next("div").find("img").attr("id",fileName);
			}
		}
	},
	//轮播图片
	editsUpload:function(e,ele){
		var fs = new FileReader(),files = e.files[0];
		var fileName = files.name;
		if(files.size>10*1024*1024 ||files.size<10*1024 ){
			console.log("======轮播图====="+files.size)
			alert("单照图片在10K-10M之间，请您重新选择图片！");
		}else {
			if(!flashImg.isSuffix(fileName)) return false;//判断图片格式
			fs.readAsDataURL(files);
			fs.onload = function (event) {
				//console.log(ele.parent("div.uploadBtnBg").siblings("img").length);
				ele.parent("div.form-inline").next("div").find("img").attr("src",this.result);
				//console.log("fileName="+files.name)
				ele.parent("div.form-inline").next("div").find("img").attr("id",fileName);
				//上传封面
				var fd = new FormData();
				var blob = dataURItoBlob(this.result);
				fd.append('file', blob,fileName);
				$.ajax({
					url : '/web-adv/uploadImgs',
					type : 'post',
					data:fd,
					processData: false, // 不会将 data 参数序列化字符串
					contentType: false, // 根据表单 input 提交的数据使用其默认的 contentType
					success : function(data) {
						var data=JSON.parse(data);
						//console.log(data.data)
						if(data.status=="1"){
							//保存 所有
							pictureUrl = data.picServerPrex+data.data;
							console.log('pictureUrl ='+pictureUrl);
						}else{
							alert("保存失败！");
						}

					},
					error: function(){}
				});
			}
		}
	},
	upload:function(ele){ //
		flashImg.editDom.parent("div.adCoverFilmsBtnGroup").siblings("img").attr("src",pictureUrl);
		ele.next().trigger("click");

	},
	uploadPage:function(ele){//修改视频封面
		var src = ele.parent("div.form-group").prev("div").find("img").attr("src");
		var fileName = ele.parent("div.form-group").prev("div").find("img").attr("id");
		if(src){
			//flashImg.editDom.siblings("div.adCoverBox").children("img").attr("src",src);
			//上传封面
			var fd = new FormData();
			var blob = dataURItoBlob(src);
			fd.append('file', blob,fileName);
			$.ajax({
				url : '/web-adv/uploadImgs',
				type : 'post',
				data:fd,
				processData: false, // 不会将 data 参数序列化字符串
				contentType: false, // 根据表单 input 提交的数据使用其默认的 contentType
				success : function(data) {
					var data=JSON.parse(data);
					if(data.status=="1"){
						//保存 所有
						adHomePageUrl = data.data;
						$("#adHomeimage").attr("src",src);
					}else{
						alert("保存失败！");
					}

				},
				error: function(){}
			});

			ele.next().trigger("click");
		}
	},
	setting:function(ele){//把轮播图设置为图片广告封面
		var src = flashImg.settingDom.parent("div.adCoverFilmsBtnGroup").siblings("img").attr("src");
		var fileNmae = flashImg.settingDom.parent("div.adCoverFilmsBtnGroup").siblings("img").attr("id");
		$("#adHomeimage").attr("src",src);
		//判断是否为base64编码
		if(src.indexOf("data:image") != -1){
			//转化保存
			var fd = new FormData();
			var blob = dataURItoBlob(src);
			fd.append('file', blob,fileNmae);
			$.ajax({
				url : '/web-adv/uploadImgs',
				type : 'post',
				data:fd,
				processData: false, // 不会将 data 参数序列化字符串
				contentType: false, // 根据表单 input 提交的数据使用其默认的 contentType
				success : function(data) {
					var data=JSON.parse(data);
					//console.log(data.data)
					if(data.status=="1"){
						//图片封面
						adHomePageUrl = data.data;
					}else{
						alert("保存失败！");
					}

				},
				error: function(){}
			});
		}
		ele.next().trigger("click");
	},
	settingDom:"",
	goSetting:function(ele){
		flashImg.settingDom = ele;
	},
	isSuffix:function(ele){
		ele = ele.substring(ele.lastIndexOf(".")+1,ele.length);
		ele=ele.toUpperCase();//jpg、gif、png
		if(ele!="PNG"&&ele!="GIF"&&ele!="JPEG"&&ele!="JPG"){
			alert("请您上传jpg、gif、png格式的图片！")
			return false;
		}
		return true;
	}
};